package com.ravi.service.impl;

import com.ravi.common.constant.CheckExceptionEnum;
import com.ravi.common.exception.CheckException;
import com.ravi.common.utils.md5.MD5Utils;
import com.ravi.mapper.AdminUserMapper;
import com.ravi.model.entity.AdminUser;
import com.ravi.model.query.AdminPassQuery;
import com.ravi.model.vo.AdminUserVo;
import com.ravi.service.intf.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.security.NoSuchAlgorithmException;

@Service
public class UserServiceImpl implements UserService {

	@Autowired
	private AdminUserMapper adminUserMapper;

	@Override
	public AdminUserVo adminUserLogin(String username, String password) {
		String md5Password = null;
		try {
			md5Password = MD5Utils.getMD5Str(password);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		AdminUser adminUser = adminUserMapper.adminLogin(username, md5Password);
		if (adminUser == null) {
			throw new CheckException(CheckExceptionEnum.LOGIN_FAILED);
		}
		return new AdminUserVo(adminUser.getUsername(), adminUser.getName());
	}

	@Override
	public boolean isChangePassword(String username, AdminPassQuery query) throws NoSuchAlgorithmException {
		AdminUser user = adminUserMapper.selectAdminByUsername(username);
		String md5OldStr = MD5Utils.getMD5Str(query.getOldPwd());
		if (!user.getPassword().equals(md5OldStr)) {
			throw new CheckException(CheckExceptionEnum.WRONG_PASSWORD);
		}
		String md5NewStr = MD5Utils.getMD5Str(query.getNewPwd());
		user.setPassword(md5NewStr);
		int i = adminUserMapper.updateAdminPassword(user);
		return i != 0;
	}
}
